<template>
  <div class="work-process-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span>首页</span>
      <span class="separator">/</span>
      <span>工序</span>
      <el-icon class="close-icon" @click="$router.go(-1)"><Close /></el-icon>
    </div>

    <!-- 标题 -->
    <div class="page-title">
      <el-icon><Grid /></el-icon>
      <span>工序</span>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-action-bar">
      <div class="search-fields">
        <el-input
          v-model="searchForm.processCode"
          placeholder="工序编号"
          clearable
          style="width: 200px; margin-right: 10px;"
        />
        <el-input
          v-model="searchForm.processName"
          placeholder="工序名称"
          clearable
          style="width: 200px; margin-right: 10px;"
        />
        <!-- <el-input
          v-model="searchForm.workPermission"
          placeholder="报工权限"
          clearable
          style="width: 200px; margin-right: 10px;"
        /> -->
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          查询
        </el-button>
        <!-- <el-button type="primary" @click="handleAdvancedSearch">
          <el-icon><Search /></el-icon>
          高级查询
        </el-button> -->
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新建
        </el-button>
        <!-- <el-button type="primary" @click="handleEdit" :disabled="!selectedRow">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button> -->
        <el-button type="danger" @click="handleDelete" :disabled="!selectedRow">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
        <!-- <el-button type="primary" @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button> -->
        <el-button type="primary" @click="handleColumnSettings">
          <el-icon><Grid /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 主表格：工序列表 -->
    <div class="main-table">
      <el-table
        :data="workProcessList"
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="processCode" label="工序编号" width="200" />
        <el-table-column prop="processName" label="工序名称" width="150" />
        <el-table-column prop="workPermission" label="报工权限" width="200" />
        <el-table-column prop="workRatio" label="报工数配比" width="120" />
        <el-table-column prop="defectItemList" label="不良品项列表" width="300">
          <template #default="scope">
            <div v-if="scope.row.defectItemList && scope.row.defectItemList.length > 0" class="defect-list">
              <el-tag 
                v-for="(defect, index) in scope.row.defectItemList" 
                :key="`${scope.row.workProcessId}-${defect.defectItemId}`"
                size="small"
                :type="getDefectTagType(index)"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ defect.displayText }}
              </el-tag>
            </div>
            <span v-else class="no-data">暂无数据</span>
          </template>
        </el-table-column>
        <el-table-column label="采集数据" width="120">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.collectionDataList && scope.row.collectionDataList.length > 0"
              type="success"
              size="small"
            >
              {{ scope.row.collectionDataList.length }} 项
            </el-tag>
            <span v-else class="no-data">0 项</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column prop="modifier" label="修改人" width="120" />
        <el-table-column prop="modifyTime" label="修改时间" width="180" />
        <el-table-column prop="test2" label="测试2" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 子表格：工序采集数据 -->
    <div class="sub-table">
      <div class="sub-table-header">
        <el-icon><Grid /></el-icon>
        <span>工序采集数据 - {{ selectedRow ? selectedRow.processName : '请选择工序' }}</span>
      </div>
      <el-table :data="collectionDataList" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="processName" label="工序" width="150" />
        <el-table-column prop="dataType" label="类型" width="120" sortable>
          <template #default="scope">
            <el-tag v-if="scope.row.dataType" size="small" type="info">
              {{ scope.row.dataType }}
            </el-tag>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="dataName" label="名称" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.dataName" size="small" type="success">
              {{ scope.row.dataName }}
            </el-tag>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable>
          <template #default="scope">
            {{ scope.row.createTime ? new Date(scope.row.createTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column prop="modifier" label="修改人" width="120" />
        <el-table-column prop="modifyTime" label="修改时间" width="180" sortable>
          <template #default="scope">
            {{ scope.row.modifyTime ? new Date(scope.row.modifyTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 子表格分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="subPagination.pageIndex"
          v-model:page-size="subPagination.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="subPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSubSizeChange"
          @current-change="handleSubCurrentChange"
        />
      </div>
    </div>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="work-process-form"
      >
        <div class="form-row">
          <el-form-item label="工序编号" prop="processCode">
            <div class="code-input-group">
              <el-input
                v-model="form.processCode"
                placeholder="请输入,忽略将自动生成"
                :disabled="isEdit"
                style="flex: 1;"
              />
              <el-button
                v-if="!isEdit"
                type="primary"
                @click="regenerateProcessCode"
                style="margin-left: 8px;"
                size="default"
              >
                <el-icon><Refresh /></el-icon>
                重新生成
              </el-button>
            </div>
            <div class="form-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>编号格式：年月日时分秒毫秒+5位随机数，如：20241201143022123456789</span>
            </div>
          </el-form-item>
          <el-form-item label="工序名称" prop="processName">
            <el-input
              v-model="form.processName"
              placeholder="工序名称"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="报工权限" prop="workPermission">
            <el-select
              v-model="form.workPermission"
              placeholder="请选择报工权限"
              multiple
              filterable
              allow-create
              style="width: 100%"
            >
              <el-option label="所有人" value="所有人" />
              <el-option label="超级管理员" value="超级管理员" />
              <el-option label="Admin测试" value="Admin测试" />
              <el-option label="测试" value="测试" />
            </el-select>
          </el-form-item>
          <el-form-item label="报工数配比" prop="workRatio">
            <el-input-number
              v-model="form.workRatio"
              placeholder="报工数配比"
              :min="0"
              :precision="2"
              style="width: 100%"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="不良品项列表" prop="defectItemIds">
            <el-select
              v-model="form.defectItemIds"
              placeholder="请选择不良品项"
              multiple
              filterable
              clearable
              collapse-tags
              collapse-tags-tooltip
              style="width: 100%"
              :loading="defectItemsLoading"
              @visible-change="handleDefectSelectVisibleChange"
            >
              <el-option
                v-for="item in defectItemList"
                :key="item.defectItemId"
                :label="`${item.defectCode} | ${item.defectName}`"
                :value="item.defectItemId"
              >
                <div class="defect-option">
                  <span class="defect-code">{{ item.defectCode }}</span>
                  <span class="defect-name">{{ item.defectName }}</span>
                </div>
              </el-option>
            </el-select>
            <div class="form-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>支持多选，可搜索不良品编号或名称</span>
              <span v-if="selectedDefectCount > 0" class="selected-count">
                (已选择 {{ selectedDefectCount }} 项)
              </span>
            </div>
          </el-form-item>
        </div>

        <!-- 扩展字段 -->
        <div class="extension-fields">
          <div class="extension-header">扩展字段</div>
          <div class="form-row">
            <el-form-item label="测试2" prop="test2">
              <el-select
                v-model="form.test2"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="测试2" value="测试2" />
              </el-select>
            </el-form-item>
            <el-form-item label="测试" prop="test">
              <el-input
                v-model="form.test"
                placeholder="测试"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 工序采集数据 -->
        <div class="collection-data-section">
          <div class="section-header">
            <el-icon><Grid /></el-icon>
            <span>工序采集数据</span>
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" @click="addCollectionRow">
              <el-icon><Plus /></el-icon>
              添加行
            </el-button>
            <el-button type="danger" @click="deleteCollectionRow">
              <el-icon><Delete /></el-icon>
              删除行
            </el-button>
            <el-button type="primary" @click="importCollectionData">
              <el-icon><Upload /></el-icon>
              导入
            </el-button>
            <el-button type="primary" @click="refreshCollectionData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>

          <el-table
            :data="form.collectionDataList"
            @selection-change="handleCollectionSelectionChange"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="processName" label="工序" width="150" sortable />
            <el-table-column prop="dataType" label="*类型" width="120" sortable>
              <template #default="scope">
                <el-input
                  v-model="scope.row.dataType"
                  placeholder="类型"
                />
              </template>
            </el-table-column>
            <el-table-column prop="dataName" label="*名称" width="150">
              <template #default="scope">
                <el-input
                  v-model="scope.row.dataName"
                  placeholder="名称"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" sortable />
            <el-table-column prop="creator" label="创建人" width="120" />
            <el-table-column prop="modifier" label="修改人" width="120" />
            <el-table-column prop="modifyTime" label="修改时间" width="180" sortable />
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="collectionPagination.pageIndex"
              v-model:page-size="collectionPagination.pageSize"
              :page-sizes="[10, 20, 30, 50, 100]"
              :total="collectionPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">
            <el-icon><Check /></el-icon>
            保存
          </el-button>
          <el-button @click="handleDialogClose">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, Plus, Edit, Delete, Upload, Download, Grid, Close, Check, Refresh, InfoFilled
} from '@element-plus/icons-vue'
import { MES_XSP_ApiHost } from '@/utils/Interceptors'

// 响应式数据
const workProcessList = ref([])
const collectionDataList = ref([])
const defectItemList = ref([])
const defectItemsLoading = ref(false)
const selectedRow = ref(null)
const selectedRows = ref([])
const selectedCollectionRows = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  processCode: '',
  processName: '',
  workPermission: ''
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  total: 0
})

const subPagination = reactive({
  pageIndex: 1,
  pageSize: 100,
  total: 0
})

const collectionPagination = reactive({
  pageIndex: 1,
  pageSize: 100,
  total: 0
})

// 表单数据
const form = reactive({
  processCode: '',
  processName: '',
  workPermission: [],
  workRatio: 1,
  defectItemIds: [],
  test2: '',
  test: '',
  collectionDataList: []
})

// 表单验证规则
const rules = {
  processName: [
    { required: true, message: '请输入工序名称', trigger: 'blur' }
  ],
  workPermission: [
    { required: true, message: '请选择报工权限', trigger: 'change' }
  ],
  workRatio: [
    { required: true, message: '请输入报工数配比', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '工序 (编辑)' : '工序 (新建)'
})

const selectedDefectCount = computed(() => {
  return form.defectItemIds.length
})

// 获取不良品标签类型，用于显示不同颜色
const getDefectTagType = (index) => {
  const types = ['primary', 'warning', 'success', 'info', 'danger']
  return types[index % types.length]
}

// 自动生成工序编号
const generateProcessCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  const second = String(now.getSeconds()).padStart(2, '0')
  const millisecond = String(now.getMilliseconds()).padStart(3, '0')
  
  // 生成5位随机数
  const randomNum = Math.floor(Math.random() * 90000) + 10000
  
  return `${year}${month}${day}${hour}${minute}${second}${millisecond}${randomNum}`
}

// 方法
const fetchData = async () => {
  try {
    const params = {
      ...searchForm,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    const response = await MES_XSP_ApiHost.get('/api/WorkProcess/GetWorkProcessList', { params })
    console.log('工序列表API响应:', response.data);
    
    if (response.data.code === 200) {
      workProcessList.value = response.data.pageData
      pagination.total = response.data.totalCount
      
      // 调试：检查每个工序的不良品项数据
      workProcessList.value.forEach((item, index) => {
        console.log(`工序 ${index + 1}:`, {
          processName: item.processName,
          defectName: item.defectName,
          defectItemList: item.defectItemList,
          hasDefectItemList: !!item.defectItemList,
          defectItemListLength: item.defectItemList ? item.defectItemList.length : 0,
          hasDefectName: !!item.defectName,
          defectNameLength: item.defectName ? item.defectName.length : 0
        })
        
        // 详细检查defectItemList的结构
        if (item.defectItemList && item.defectItemList.length > 0) {
          console.log(`工序 ${index + 1} 的不良品项详情:`, item.defectItemList)
          item.defectItemList.forEach((defect, defectIndex) => {
            console.log(`  不良品项 ${defectIndex + 1}:`, {
              defectItemId: defect.defectItemId,
              defectCode: defect.defectCode,
              defectName: defect.defectName,
              displayText: defect.displayText,
              hasDisplayText: !!defect.displayText
            })
          })
        }
      })
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取工序列表失败:', error)
    ElMessage.error('获取数据失败')
  }
}

const fetchDefectItems = async () => {
  try {
    defectItemsLoading.value = true
    // 使用新的API接口获取所有不良品数据
    const response = await MES_XSP_ApiHost.get('/api/WorkProcess/GetAllDefectItems')
    
    if (response.data.code === 200) {
      defectItemList.value = response.data.data
    } else {
      console.error('获取不良品数据失败:', response.data.msg)
      ElMessage.warning('获取不良品数据失败，请稍后重试')
    }
  } catch (error) {
    console.error('获取不良品项失败:', error)
    ElMessage.error('获取不良品数据失败')
  } finally {
    defectItemsLoading.value = false
  }
}

// 处理不良品下拉框显示变化
const handleDefectSelectVisibleChange = (visible) => {
  if (visible && defectItemList.value.length === 0) {
    // 当下拉框打开且没有数据时，自动加载数据
    fetchDefectItems()
  }
}

const fetchCollectionData = async (workProcessId) => {
  if (!workProcessId) {
    collectionDataList.value = []
    return
  }
  
  try {
    const response = await MES_XSP_ApiHost.get(`/api/WorkProcess/GetWorkProcessById?id=${workProcessId}`)
    
    if (response.data.code === 200 && response.data.data) {
      collectionDataList.value = response.data.data.collectionDataList || []
      subPagination.total = collectionDataList.value.length
    }
  } catch (error) {
    console.error('获取工序采集数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.pageIndex = 1
  fetchData()
}

const handleAdvancedSearch = () => {
  ElMessage.info('高级查询功能待实现')
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  // 自动生成工序编号
  form.processCode = generateProcessCode()
  dialogVisible.value = true
}

// 重新生成工序编号
const regenerateProcessCode = () => {
  // 添加防抖，避免快速点击
  if (regenerateProcessCode.isGenerating) {
    return
  }
  
  regenerateProcessCode.isGenerating = true
  
  form.processCode = generateProcessCode()
  ElMessage.success('工序编号已重新生成')
  
  // 500ms后允许再次生成
  setTimeout(() => {
    regenerateProcessCode.isGenerating = false
  }, 500)
}

const handleEdit = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请先选择要编辑的行')
    return
  }
  
  isEdit.value = true
  loadFormData(selectedRow.value)
  dialogVisible.value = true
}

const handleDelete = async () => {
  if (!selectedRow.value) {
    ElMessage.warning('请先选择要删除的行')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除选中的工序吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await MES_XSP_ApiHost.delete(`/api/WorkProcess/DeleteWorkProcess?id=${selectedRow.value.workProcessId}`)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
      selectedRow.value = null
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleImport = () => {
  ElMessage.info('导入功能待实现')
}

const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

const handleColumnSettings = () => {
  ElMessage.info('列设置功能待实现')
}

const handleRowClick = (row) => {
  selectedRow.value = row
  // 直接使用工序数据中的采集数据，避免额外的API调用
  if (row.collectionDataList && row.collectionDataList.length > 0) {
    collectionDataList.value = row.collectionDataList
    subPagination.total = row.collectionDataList.length
  } else {
    collectionDataList.value = []
    subPagination.total = 0
  }
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleCollectionSelectionChange = (selection) => {
  selectedCollectionRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchData()
}

const handleCurrentChange = (page) => {
  pagination.pageIndex = page
  fetchData()
}

const handleSubSizeChange = (size) => {
  subPagination.pageSize = size
}

const handleSubCurrentChange = (page) => {
  subPagination.pageIndex = page
}

const resetForm = () => {
  Object.assign(form, {
    processCode: '',
    processName: '',
    workPermission: [],
    workRatio: 1,
    defectItemIds: [],
    test2: '',
    test: '',
    collectionDataList: []
  })
}

const loadFormData = (row) => {
  Object.assign(form, {
    processCode: row.processCode,
    processName: row.processName,
    workPermission: row.workPermission ? row.workPermission.split(',') : [],
    workRatio: row.workRatio,
    defectItemIds: [], // 先清空，后面通过API获取关联的不良品项
    test2: row.test2,
    test: row.test,
    collectionDataList: row.collectionDataList || []
  })
  
  // 获取工序详情以获取关联的不良品项
  fetchWorkProcessDetail(row.workProcessId)
}

// 获取工序详情
const fetchWorkProcessDetail = async (workProcessId) => {
  try {
    const response = await MES_XSP_ApiHost.get(`/api/WorkProcess/GetWorkProcessById?id=${workProcessId}`)
    
    if (response.data.code === 200 && response.data.data) {
      const detail = response.data.data
      
      // 根据关联的不良品项名称，找到对应的ID
      if (detail.defectName) {
        const defectNames = detail.defectName.split(', ')
        const defectIds = []
        
        defectNames.forEach(defectName => {
          const defectItem = defectItemList.value.find(item => 
            defectName.includes(item.defectCode) || defectName.includes(item.defectName)
          )
          if (defectItem) {
            defectIds.push(defectItem.defectItemId)
          }
        })
        
        form.defectItemIds = defectIds
      }
    }
  } catch (error) {
    console.error('获取工序详情失败:', error)
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    // 如果是新建且编号为空，自动生成编号
    if (!isEdit.value && (!form.processCode || form.processCode.trim() === '')) {
      form.processCode = generateProcessCode()
    }
    
    const submitData = {
      ...form,
      workPermission: Array.isArray(form.workPermission) ? form.workPermission.join(',') : form.workPermission,
      defectItemIds: form.defectItemIds || [], // 确保不良品项ID列表正确传递
      collectionDataList: form.collectionDataList || [] // 确保工序采集数据正确传递
    }
    
    console.log('提交数据:', submitData)
    
    const url = isEdit.value ? '/api/WorkProcess/UpdateWorkProcess' : '/api/WorkProcess/CreateWorkProcess'
    const method = isEdit.value ? 'put' : 'post'
    
    // 增加超时时间到30秒，因为工序创建涉及多个表的操作
    const response = await MES_XSP_ApiHost[method](url, submitData, { timeout: 30000 })
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(response.data.msg || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

const addCollectionRow = () => {
  form.collectionDataList.push({
    processName: form.processName || '',
    dataType: '',
    dataName: '',
    creator: 'admin'
  })
}

const deleteCollectionRow = () => {
  if (selectedCollectionRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }
  
  const selectedIds = selectedCollectionRows.value.map(row => row.processCollectionDataId)
  form.collectionDataList = form.collectionDataList.filter(
    item => !selectedIds.includes(item.processCollectionDataId)
  )
  ElMessage.success('删除成功')
}

const importCollectionData = () => {
  ElMessage.info('导入功能待实现')
}

const refreshCollectionData = () => {
  ElMessage.info('刷新功能待实现')
}

// 生命周期
onMounted(() => {
  fetchData()
  // 预加载不良品数据，提供更好的用户体验
  fetchDefectItems()
})
</script>

<style scoped>
.work-process-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.breadcrumb {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.separator {
  margin: 0 8px;
  color: #ccc;
}

.close-icon {
  margin-left: auto;
  cursor: pointer;
  color: #999;
}

.close-icon:hover {
  color: #409eff;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
}

.search-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-fields {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.main-table {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sub-table {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sub-table-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.sub-table-header .el-icon {
  margin-right: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.defect-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.defect-link {
  color: #409eff;
  cursor: pointer;
}

.defect-link:hover {
  text-decoration: underline;
}

.no-data {
  color: #909399;
  font-style: italic;
}

.work-process-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row .el-form-item {
  flex: 1;
}

.extension-fields {
  margin: 20px 0;
  padding: 15px;
  background: linear-gradient(135deg, #67c23a, #409eff);
  border-radius: 8px;
}

.extension-header {
  color: white;
  font-weight: bold;
  margin-bottom: 15px;
  font-size: 16px;
}

.collection-data-section {
  margin-top: 30px;
}

.section-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.section-header .el-icon {
  margin-right: 8px;
}

.collection-data-section .action-buttons {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.dialog-footer .el-button {
  min-width: 100px;
}

/* 不良品选项样式 */
.defect-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.defect-code {
  font-weight: bold;
  color: #409eff;
  font-size: 12px;
}

.defect-name {
  color: #606266;
  font-size: 14px;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.form-tip .el-icon {
  font-size: 12px;
}

.selected-count {
  color: #409eff;
  font-weight: 500;
  margin-left: 8px;
}

.code-input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.code-input-group .el-input {
  flex: 1;
}

.code-input-group .el-button {
  flex-shrink: 0;
}

/* 下拉框选中项样式 */
:deep(.el-select .el-select__tags) {
  max-width: calc(100% - 30px);
}

:deep(.el-select .el-select__tags .el-tag) {
  margin: 2px 4px 2px 0;
  max-width: 200px;
}

:deep(.el-select .el-select__tags .el-tag .el-tag__content) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
